package com.supreme.simpleserver.component;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@ServerEndpoint(value = "/sync/{userId}")
@Component
public class WebSocketServer {

    /**
     * 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static final AtomicInteger onlineNum = new AtomicInteger();

    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
     */
    private static final ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    /**
     * 接收userId
     */
    private String userId = null;

    public static void addOnlineCount() {
        onlineNum.incrementAndGet();
    }

    public static void subOnlineCount() {
        onlineNum.decrementAndGet();
    }

    //发送消息
    private void sendMessage(Session session, String message) throws IOException {
        if (session != null) {
            synchronized (session) {
                session.getBasicRemote().sendText(message);
            }
        }
    }

    /**
     * 给指定用户发送信息
     * @param userId
     * @param message
     */
    private void sendInfo(String userId, String message) {
        Session session = sessionPools.get(userId);
        try {
            sendMessage(session, message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 建立连接
     * @param session
     * @param userId
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") String userId) {
        if (!sessionPools.containsKey(userId)) {
            addOnlineCount();
        }

        sessionPools.put(userId, session);
        this.userId = userId;
        System.out.printf("<<onOpen>> userId: [%s] connected socket, connect number: [%s]\n", userId, onlineNum);

        try {
            sendMessage(session, "欢迎" + userId + "加入连接！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭连接
     * @param session
     * @param userId
     */
    @OnClose
    public void onClose(Session session, @PathParam(value = "userId") String userId) {
        sessionPools.remove(userId);
        subOnlineCount();
        System.out.printf("<<onClose>> userId: [%s] disconnected socket, connect number: [%s]\n", userId, onlineNum);
    }

    /**
     * 收到客户端信息
     * @param message
     */
    @OnMessage
    public void onMessage(String message) throws IOException {
        System.out.printf("onMessage userId: [%s] message: [%s]\n", this.userId, message);

        if (sessionPools.containsKey(this.userId)) {
            sessionPools.get(this.userId).getBasicRemote().sendText("re:" + message);
        }
    }

    /**
     * 连接错误
     * @param session
     * @param throwable
     */
    @OnError
    public void onError(Session session, Throwable throwable) {
        System.out.println("<<onError>> 发生错误");
        throwable.printStackTrace();
    }
}
